﻿using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using ZilLion.Core.DatabaseWrapper.Dapper;
using ZilLion.Core.DatabaseWrapper.SqlServer;
using ZilLion.Core.Unities;

namespace ZilLion.Task.Domain.Respository
{
    public class TaskRunLogRespository : SqlServerRespository<TaskRunLogEntity>
    {
        public TaskRunLogRespository()
        {
            Context = new TaskRunnerContext();
        }

        /// <summary>
        ///     获取当前serverid所有记录
        /// </summary>
        /// <returns></returns>
        public IList<TaskRunLogEntity> GetAllTaskRunLog(string serverid)
        {
            return
                GetList(@"select * from task_run_log where taskserverid=@serverid",
                    new {serverid = serverid}).ToList();
        }

        /// <summary>
        ///     清空当前serverid所有记录
        /// </summary>
        public void ClearTaskRunLog()
        {
            DapperHelper.Execute(@"delete from task_run_log where taskserverid=@serverid", Context,
                new {serverid = ConfigurationManager.AppSettings["TaskServerId"]});
        }

        /// <summary>
        ///     按ID 或者log
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public TaskRunLogEntity GetTaskRunLogById(string taskid)
        {
            return
                GetList(@"select * from task_run_log where taskid=@taskid and taskserverid=@serverid",
                    new {serverid = ConfigurationManager.AppSettings["TaskServerId"], taskid}).FirstOrDefault();
        }


        /// <summary>
        ///     修改
        /// </summary>
        /// <param name="logEntity"></param>
        public void SaveTaskRunLog(TaskRunLogEntity logEntity)
        {
            var old = GetTaskRunLogById(logEntity.Taskid);
            if (old != null)
                Modify(logEntity);
            else
                Add(logEntity);
        }

        /// <summary>
        ///     删除
        /// </summary>
        /// <param name="logEntity"></param>
        public void RemoveTaskRunLog(TaskRunLogEntity logEntity)
        {
            Remove(logEntity);
        }
    }
}